package com.wuxianedu.sqliteopenhelperdemo;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.wuxianedu.sqliteopenhelperdemo.db.DBHelper;

import java.util.List;

/**
 * Created by TED on 2016/9/19.
 */
public class ListActivity extends AppCompatActivity {


    private DBHelper db;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list);
        ListView listview = (ListView) findViewById(R.id.list_view_id);
        db = new DBHelper(ListActivity.this);
        listview.setAdapter(new MyAdapter());

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        db.close();
    }

    class MyAdapter extends BaseAdapter {
        private List<Person> list;

        public MyAdapter() {

            list = db.queryData();
        }

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            Holder holder;
            if (convertView == null) {
                holder = new Holder();
                convertView = View.inflate(ListActivity.this, R.layout.item_list, null);
                holder.name = (TextView) convertView.findViewById(R.id.item_name);
                holder.age = (TextView) convertView.findViewById(R.id.item_age);
                holder.love = (TextView) convertView.findViewById(R.id.item_love);
                convertView.setTag(holder);
            } else {
                holder = (Holder) convertView.getTag();
            }

            holder.name.setText(list.get(position).getName());
            holder.age.setText(list.get(position).getAge());
            holder.love.setText(list.get(position).getLove());
            return convertView;
        }

        class Holder {
            TextView name, age, love;
        }
    }
}
